package com.xinchao.job.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xinchao.common.constant.CacheConstant;
import com.xinchao.common.vo.AdministratorVO;
import com.xinchao.core.cache.redis.RedisCacheDao;
import com.xinchao.job.mapper.dmp.UserMapper;

/**
 * 
 * <p>Title: UserService</p>  
 * <p>Description: 查询系统用户</p>  
 * @author huangf 
 * @date 2018年9月27日
 */
@Service(value = "userService")
public class UserService {
	private static Logger logger = LoggerFactory.getLogger(UserService.class);
	@Autowired
	private RedisCacheDao redisCacheDao;
	@Autowired
	private UserMapper userMapper;

	public Map<Object, Object> getAdminUserMap() {
		Map<Object, Object> adminUserMap = new HashMap<>();
		try {
			try {
				// 获取缓存中的管理人员联系信息
				adminUserMap = redisCacheDao.getAllCache(CacheConstant.CACHE_NAME_ADMIN_USER_CONTACT);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage(),e);
			}
			if ( adminUserMap.isEmpty() ) {
				// 缓存中的信息为空则查询数据库
				List<AdministratorVO> allAdmin = userMapper.getAllAdministrator();
				if ( CollectionUtils.isNotEmpty(allAdmin) ) {
					for ( AdministratorVO vo : allAdmin ) {
						adminUserMap.put(vo.getUserId(), vo);
					}
					try {
						// 将查询到的数据放入缓存中设置过期时间为24小时
						redisCacheDao.putAllCache(CacheConstant.CACHE_NAME_ADMIN_USER_CONTACT, adminUserMap);
						redisCacheDao.expire(CacheConstant.CACHE_NAME_ADMIN_USER_CONTACT, 24L, TimeUnit.HOURS);
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage(),e);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return adminUserMap;
	}
}